package listbyorder.access001_100.test47;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/1 8:18
 */
public class Solution1 {

    // 全排列2，考虑重复的情况
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) return res;
        boolean[] hasUse = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(res, nums, hasUse, new ArrayDeque<Integer>());
        return res;
    }

    private void dfs(List<List<Integer>> res, int[] nums, boolean[] hasUse, ArrayDeque<Integer> path) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!hasUse[i]) {
                // 相比于46题，只加了这一行代码
                if(i > 0 && nums[i] == nums[i - 1] && !hasUse[i - 1]){
                    continue;
                }
                hasUse[i] = true;
                path.addLast(nums[i]);
                dfs(res, nums, hasUse, path);
                path.removeLast();
                hasUse[i] = false;   // 回溯
            }
        }
    }
}
